// 相关配置
const config = {
	development: {
		// 开发环境服务端地址，本地调试域名
		host: "https://gys.ohyeah123.cn"
	},
	production: {
		// 生产环境服务端地址，编译后自动启用该地址
		host: "https://gys.ohyeah123.cn"
	},
	// 身份认证状态码
	authErrorStatusCode: 401,
	// 登录页面路径
	loginPage: "/pages/login/login",
	// 跳转登录页面方式
	navigateLoginPageType: "reLaunch",
	// 接口异常提醒
	errorMessage: "服务器异常",
	// 认证token
	tokenField: '__token__',
	// 认证token
	shopidField: '__shopid__',
	// 腾讯地图，请更换为自己的 key 否则有次数限制
	qqmapsdk: {
		key: 'QUSBZ-FUFLU-X2SV5-2UXFE-KVWRJ-C5FBE'
	},

}
// 开发环境
const env = process.env.NODE_ENV;
const uploadUrl = 'https://app.yssq.com.cn/api/common/upload'
console.log('当前环境：' + env);
// 平台
const platform = uni.getSystemInfoSync().platform;
// 封装消息提示方法
const toast = (message) => {
	uni.showToast({
		title: message,
		duration: 2000,
		icon: 'none'
	});
}
// 对象转url参数
const parseParam = (param) => {
	let paramArray = [];
	for (let [key, value] of Object.entries(param)) {
		paramArray.push(key + '=' + value);
	}
	return paramArray.join('&');
}
// 设置用户表示符
const setUserToken = (token) => {
	return uni.setStorageSync(config.tokenField, token);
}
// 设置用户表示符
const setUserShopid = (shopid) => {
	return uni.setStorageSync(config.shopidField, shopid);
}
const clearUsetToken = () => {
	return uni.clearStorage(config.tokenField);
}
const clearUsetShopid = () => {
	return uni.clearStorage(config.shopidField);
}
// 获取用户身份标示
const getUserToken = () => {
	return uni.getStorageSync(config.tokenField);
}
const getUserShopid = () => {
	return uni.getStorageSync(config.shopidField);
}
//判断是否登录
const hasLogin = () => {
	let token = uni.getStorageSync(config.tokenField);
	return token ? true : false;
}
// 封装get方法
const get = (url, data) => {
	let token = uni.getStorageSync(config.tokenField);
	let shopid = uni.getStorageSync(config.shopidField);
	let push_clientid = uni.getStorageSync('push_clientid');
	if (data) {
		data.token = token
	} else {
		data = {
			token
		}
	}
	if (data) {
		// data.supplyer_code = shopid
		data.push_clientid = push_clientid
	}
	console.log('请求参数',data)
	return new Promise((resolve, reject) => {
		uni.request({
			url: config[env].host + url,
			data: data,
			header: {
				'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8'
			},
			complete: (res) => {
				if (res.statusCode == config.authErrorStatusCode) {
					let pages = getCurrentPages()
					console.log('pages', pages)
					if (pages[pages.length - 1].$page.fullPath != config.loginPage) {
						console.log('已经跳转登录页面')
						uni.removeStorageSync(config.tokenField);
						uni.showModal({
							title: '提示',
							content: '暂未登录，请登录后操作',
							success() {
								uni[config.navigateLoginPageType]({
									url: config.loginPage
								});
							}
						})

					}
					return false;
				}
				if (res.statusCode == 200) {
					console.log(res.data)
					if (res.data.code == 0) {
						uni.showModal({
							title:'温馨提示',
							content: res.data.msg,
							icon: "error"
						})
					} else {
						resolve(res.data);
					}
				} else {
					toast(config.errorMessage);
					reject(res);
				}
			}
		})
	})
}

// 封装post方法
const post = (url, data) => {
	let token = uni.getStorageSync(config.tokenField);
	let shopid = uni.getStorageSync(config.shopidField);
	if (data) {
		data.token = token
	} else {
		data = {
			token
		}
	}
	if (!data.shopid) {
		// data.supplyer_code = shopid
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: config[env].host + url,
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8'
			},
			data: data,
			method: 'POST',
			complete: (res) => {
				if (res.statusCode == config.authErrorStatusCode) {
					uni.removeStorageSync(config.tokenField);
					uni[config.navigateLoginPageType]({
						url: config.loginPage
					});
					return false;
				}
				if (res.statusCode == 200) {
					if (res.data.code == 0) {
						uni.showModal({
							title:'温馨提示',
							content: res.data.msg,
							icon: "error"
						})
						reject(res.data);
					} else {
						resolve(res.data);
					}
				} else {
					toast(config.errorMessage);
					reject(res);
				}
			}
		})
	})
}

const date = (timestamp) => {
	// 获取当前日期
	const date = timestamp ? new Date(timestamp) : new Date();

	// 获取当前月份
	const nowMonth = date.getMonth() + 1;

	// 获取当前是几号
	let strDate = date.getDate();

	// 添加分隔符“-”
	const seperator = "-";

	// 对月份进行处理，1-9月在前面添加一个“0”
	if (nowMonth >= 1 && nowMonth <= 9) {
		nowMonth = "0" + nowMonth;
	}

	// 对月份进行处理，1-9号在前面添加一个“0”
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}

	// 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
	return date.getFullYear() + seperator + nowMonth + seperator + strDate;
}
//下载文件
const download = (e) => {
	let that = this
	uni.downloadFile({
		url: e, //下载地址，后端接口获取的链接
		success: (data) => {
			console.log(data.tempFilePath)
			console.log(JSON.stringify(data))
			if (data.statusCode === 200) {
				uni.saveFile({ //文件保存到本地
					tempFilePath: data.tempFilePath, //临时路径
					success: function(res) {
						console.log("下载成功" + res.savedFilePath)
						console.log(JSON.stringify(res))
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '文件已保存!',
							duration: 3000,
						});
						uni.openDocument({
							showMenu: true,
							filePath: res.savedFilePath,
							success: function(res) {
								console.log('打开文档成功');
							}
						});
					}
				});
			}
		},
		fail: (err) => {
			console.log(err);
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '失败请重新下载',
			});
		},
	});
}
const develop = () => {
	uni.showToast({
		icon: 'none',
		title: '功能优化中'
	})
}
const GetAge = (identityCard) => {
	var len = (identityCard + "").length;
	if (len == 0) {
		return 0;
	} else {
		if ((len != 15) && (len != 18)) //身份证号码只能为15位或18位其它不合法
		{
			return 0;
		}
	}
	var strBirthday = "";
	if (len == 18) //处理18位的身份证号码从号码中得到生日和性别代码
	{
		strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12,
			2);
	}
	if (len == 15) {
		strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard
			.substr(10, 2);
	}
	//时间字符串里，必须是“/”
	var birthDate = new Date(strBirthday);
	var nowDateTime = new Date();
	var age = nowDateTime.getFullYear() - birthDate.getFullYear();
	//再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
	if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() &&
			nowDateTime.getDate() < birthDate.getDate())) {
		age--;
	}
	return age;
}
const navigate = (url, type = 0) => {
	switch (type) {
		case 0:
			uni.navigateTo({
				url: url
			})
			break;
		case 1:
			uni.reLaunch({
				url: url
			})
			break;
		case 2:
			uni.redirectTo({
				url: url
			})
			break;
		case 3:
			uni.switchTab({
				url: url
			})
			break;
		default:
			break;
	}
}
const showImg = (url) => {
	uni.previewImage({
		urls: [url]
	})
}
const confirm = (content, f, t) => {
	uni.showModal({
		title: '提示',
		content: content,
		cancelText:'修改',
		success(res) {
			if (res.confirm) {
				if (f()) {
					f();
				}
			} else {
				if (t) {
					t();
				}
			}
		}
	})
}
const imgDeal=(str)=>{
  return str.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;"');
}
export default {
	host: config[env].host,
	env,
	uploadUrl,
	platform,
	get,
	post,
	parseParam,
	hasLogin,
	toast,
	setUserToken,
	date,
	config,
	getUserToken,
	clearUsetToken,
	setUserShopid,
	getUserShopid,
	clearUsetShopid,
	download,
	develop,
	navigate,
	showImg,
	GetAge,
	confirm,
	imgDeal
}